#include "drv_wifi.h"
//UART3_RX->PB11,UART3_TX->PB10
void drv_usart3_init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	USART_InitTypeDef USART_InitStruct;
	NVIC_InitTypeDef NVIC_InitStruct;

	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);//开GPIOG时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);//开USART6时钟
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;//复用
	GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;//推挽
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;//使能上拉
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStruct);

	GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_USART3);//将PG9复用为USART6
	GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_USART3);//将PG14复用为USART6
	
	USART_InitStruct.USART_BaudRate = 115200;//波特率
	USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//不使用串口的硬件流控模式
	USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//能接收能发送
	USART_InitStruct.USART_Parity = USART_Parity_No;//无校验位
	USART_InitStruct.USART_StopBits = USART_StopBits_1;//1位停止位
	USART_InitStruct.USART_WordLength = USART_WordLength_8b;//8位数据位
	USART_Init(USART3, &USART_InitStruct);
	USART_ClearFlag(USART3, USART_FLAG_TC);//清除发送完成标志
	USART_Cmd(USART3, ENABLE);

	USART_ITConfig(USART3, USART_IT_RXNE,ENABLE);//串口的“接收数据寄存器非空”中断
	NVIC_InitStruct.NVIC_IRQChannel = USART3_IRQn;//中断通道
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;//抢占优先级
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;//响应优先级
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;//使能中断通道
	NVIC_Init(&NVIC_InitStruct);
	
}

void SendATCommand(char *command, char *response, int timeout) 
{
    // 清空接收缓冲区
    memset(USART_RX_BUF, 0, sizeof(USART_RX_BUF)); 
    HAL_UART_Transmit(&huart1, (uint8_t *)command, strlen(command), 1000); 
    uint32_t start_time = HAL_GetTick();
    while (1) {
        if (USART_RX_STA & 0x8000) { 
            break;
        }
        if (HAL_GetTick() - start_time > timeout) { 
            break;
        }
    }
    if (USART_RX_STA & 0x8000) { 
        USART_RX_BUF[USART_RX_STA & 0x7FFF] = '\0'; 
        if (strstr((const char *)USART_RX_BUF, response)!= NULL) { 
            // 匹配到响应
        } else {
            // 未匹配到响应
        }
    } else {
        // 接收超时
    }
    USART_RX_STA = 0; 
}
void WiFiConnect(const char *ssid, const char *password) {
    char command[100];
    sprintf(command, "AT+CWJAP=\"%s\",\"%s\"\r\n", ssid, password);
    SendATCommand(command, "OK", 5000); 
}


